import { baseInfo, Env } from '@/baseInfo';
import axios from 'axios'; //引用axios
// 先获取基础URL
let BASEURL = baseInfo().baseUrl + baseInfo().baseApi;
// axios配置
axios.defaults.timeout = 30000;
axios.defaults.baseURL = BASEURL; //这是调用数据接口
axios.defaults.withCredentials = true; //让ajax携带cookie
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
// 请求拦截器
axios.interceptors.request.use(
  config => config,
  err => Promise.reject(err)
);
// 响应拦截器
axios.interceptors.response.use(
  function (response) {
    if (response.data.code === '401') {
      localStorage.clear();
      window.location.href = ''; //跳转到登录页
    }
    return response;
  },
  err => Promise.reject(err)
);
const defaultHeader = (header = {}) => ({ 'content-type': 'application/json;charset=UTF-8', Authorization: uni.getStorageSync('ACCESS_TOKEN'), ...header });
const appRequest = async ({ url, fullUrl = false, data = {}, header = {}, method = 'POST', dataType = 'json', showLoading = true, timeout = 30000 }) => {
  const requestUrl = fullUrl ? url : BASEURL + url;
  showGlobalLoading('加载中...', showLoading);
  try {
    const rheader = await defaultHeader(header);
    const res = await new Promise((resolve, reject) => uni.request({ url: requestUrl, data, header: rheader, method, dataType, timeout, success: resolve, fail: reject }));
    hideGlobalLoading();
    // 统一错误处理
    if (res.statusCode !== 200) {
      const errorMsg = `请求失败: ${res.statusCode}`;
      uni.showToast({ title: errorMsg, icon: 'none', duration: 2000 });
      throw new Error(errorMsg);
    }
    // 业务错误处理
    if (res.data.code === 401) {
      uni.removeStorageSync('ACCESS_TOKEN');
      uni.navigateTo({ url: `/pages/global/login/login` });
      throw new Error('未授权，请重新登录');
    } else if (res.data.code !== 200 && showLoading) {
      // 显示业务错误信息
      uni.showToast({ title: res.data.msg || '请求失败', icon: 'none', duration: 2000 });
    }
    return res.data;
  } catch (err) {
    hideGlobalLoading();
    // 统一错误提示
    if (!(err instanceof Error) || err.message !== '未授权，请重新登录') {
      const errorMsg = err.errMsg || '请求错误！';
      uni.showToast({ title: errorMsg, icon: 'none', duration: 2000 });
    }
    throw err;
  }
};
const appUpload = async ({ url, fullUrl = false, filePath, header = { 'content-type': 'multipart/form-data' }, showLoading = true, timeout = 60000, name = 'file' }) => {
  showGlobalLoading('上传中...', showLoading);
  try {
    const rheader = await defaultHeader(header);
    let res = await new Promise((resolve, reject) => uni.uploadFile({ url: fullUrl ? url : BASEURL + url, header: rheader, filePath, name, timeout, success: resolve, fail: reject }));
    hideGlobalLoading();
    // 解析返回的JSON数据
    try {
      const data = JSON.parse(res.data);
      return data;
    } catch (e) {
      // JSON解析错误处理
      uni.showToast({ title: '数据解析错误', icon: 'none', duration: 2000 });
      throw new Error('上传成功但数据解析失败');
    }
  } catch (err) {
    hideGlobalLoading();
    // 统一错误提示
    if (!(err instanceof Error) || err.message !== '上传成功但数据解析失败') {
      const errorMsg = err.errMsg || '上传失败';
      uni.showToast({ title: errorMsg, icon: 'none', duration: 2000 });
    }
    throw err;
  }
};
const h5Request = async ({ url, fullUrl = false, data = {}, header = {}, method = 'POST', dataType = 'json', showLoading = true, timeout = 30000 }) => {
  const requestUrl = fullUrl ? url : BASEURL + url;
  showGlobalLoading('加载中...', showLoading);
  try {
    const rheader = await defaultHeader(header);
    const res = await axios({ method, url: requestUrl, data, withCredentials: true, responseType: dataType, timeout, headers: rheader });
    hideGlobalLoading();
    // 统一错误处理
    if (res.status !== 200) {
      const errorMsg = `请求失败: ${res.status}`;
      uni.showToast({ title: errorMsg, icon: 'none', duration: 2000 });
      throw new Error(errorMsg);
    }
    // 业务错误处理
    if (res.data.code === 401) {
      if ('/app/appUser/dissolution' === url) {
        uni.showToast({ title: '账号注销成功', icon: 'none', duration: 2000 });
      } else {
        uni.showToast({ title: '未授权，请重新登录', icon: 'none', duration: 2000 });
      }
      localStorage.clear();
      let uid = setTimeout(() => {
        clearTimeout(uid);
        window.location.href = '/pages/global/login/login';
        throw new Error('未授权，请重新登录');
      }, 2000);
    } else if (res.data.code !== 200 && showLoading) {
      // 显示业务错误信息
      uni.showToast({ title: res.data.msg || '请求失败', icon: 'none', duration: 2000 });
    }
    return res.data;
  } catch (err) {
    hideGlobalLoading();
    // 统一错误提示
    if (!(err instanceof Error) || err.message !== '未授权，请重新登录') {
      const errorMsg = err.message || '请求错误！';
      uni.showToast({ title: errorMsg, icon: 'none', duration: 2000 });
    }
    throw err;
  }
};
// 统一请求函数 - 根据环境判断调用appRequest还是h5Request
export const request = async ({ url, fullUrl = false, data = {}, header = {}, method = 'POST', dataType = 'json', showLoading = true, timeout = 30000 }) => {
  if (Env() === 'H5') {
    return await h5Request({ url, fullUrl, data, header, method, dataType, showLoading, timeout });
  } else {
    return await appRequest({ url, fullUrl, data, header, method, dataType, showLoading, timeout });
  }
};
// 统一上传函数 - 根据环境判断调用appUpload还是h5Request
export const uploadFile = async ({ url, filePath, showLoading = true }) => {
  if (Env() === 'H5') {
    return await h5Request({ url, data: filePath, header: { 'Content-Type': 'multipart/form-data' }, showLoading });
  } else {
    // App环境调用appUpload
    return await appUpload({ url, filePath, showLoading });
  }
};
// 全局loading计数，防止多次调用导致loading提前关闭
let loadingCount = 0;
// 全局显示loading函数
const showGlobalLoading = (title = '加载中...', showLoading = true) => {
  if (showLoading) {
    if (loadingCount === 0) {
      uni.showLoading({ title: title, mask: true });
    }
    loadingCount++;
  }
};
// 全局隐藏loading函数
const hideGlobalLoading = (showLoading = true) => {
  if (showLoading) {
    loadingCount--;
    if (loadingCount <= 0) {
      loadingCount = 0;
      uni.hideLoading();
    }
  }
};
